<?php

namespace app\api\logic;

use app\common\exception\BusinessException;
use app\common\model\UserCourse;
use think\facade\Db;

class ActivationCode
{
    /**
     * 确认激活
     * @param array $param
     * @return void
     * @throws
     */
    public function confirm(array $param = [])
    {
        // 提取参数
        $code = $param['code'];
        $userId = $param['userId'];
        $businessId = $param['business_id'];
        $businessType = $param['business_type'];

        // 查询激活码是否存在
        $where = [
            'code' => $code
        ];
        $model = app(\app\common\model\ActivationCode::class);
        $info = $model->where($where)->find();
        if (!$info) {
            throw new BusinessException('激活码不存在');
        }
        if ($info['use_uid'] > 0) {
            throw new BusinessException('激活码已被使用');
        }

        // 使用激活码
        $model->startTrans();

        // 开通权益
        if ($businessType == 1) {
            throw new BusinessException('暂不支持的权益类型');
        } elseif ($businessType == 2) {
            $this->activationCourse($userId, $businessId, $info);
        } elseif ($businessType == 3) {
            throw new BusinessException('暂不支持的权益类型');
        } else {
            throw new BusinessException('暂不支持的权益类型');
        }

        // 更新激活码为已使用
        $time = time();
        $updateData = [
            'use_uid' => $userId,
            'use_time' => $time,
            'use_business_id' => $businessId,
            'use_business_type' => $businessType,
            'update_time' => $time,
            'use_status' => 1,
            'sale_status' => 1
        ];
        $isUpdate = $model->where($where)->update($updateData);
        if (!$isUpdate) {
            throw new BusinessException('更新数据失败');
        }

        // 提交事务
        $model->commit();
    }

    /**
     * 激活题库
     * @throws
     */
    private function activationCourse($user_id, $course_id, $codeInfo)
    {
        // 查询题库信息
        $courseInfo = app(\app\common\model\Course::class)->getInfo($course_id);
        if (!$courseInfo) {
            throw new BusinessException('题库不存在');
        }

        // 检查激活码面值是否足够兑换课程
        $codePrice = $codeInfo['price'];
        $coursePrice = $courseInfo['price'];
        if ($codePrice < $coursePrice) {
            throw new BusinessException('激活码面值不足');
        }

        // 进行充值题库
        $expire = 86400 * 365 * 3;
        (new UserCourse())->setExpire($user_id, $course_id, $expire);
    }
}